package main

import (
	"fmt"
	"sort"
)

func equal(x, y map[string]int) bool {
	if len(x) != len(y) {
		return false
	}
	for key, xValue := range x {
		if yValue, ok := y[key]; !ok || yValue != xValue {
			return false
		}
	}
	return true
}

func main() {
	ages := map[string]int{
		"gjk":   18,
		"hhh":   22,
		"Alvin": 23,
		"hello": 38,
	}
	ages["gjk"] += 5 // 23
	ages["hhh"]++    // 23
	ages["test"] = 29
	delete(ages, "hello")
	// 每次遍历结果都是随机的，强制要求程序不依赖具体的哈希函数
	for name, age := range ages {
		fmt.Printf("%s\t%d\n", name, age)
	}
	fmt.Println()

	// 创建一个刚好放下所有名字的slice，大小合适
	names := make([]string, 0, len(ages))
	// name存入slice后排序，再根据排序后的slice去获取对应的age
	for name := range ages {
		names = append(names, name)
	}
	sort.Strings(names)
	for _, name := range names {
		fmt.Printf("%s\t%d\n", name, ages[name])
	}
	fmt.Println()

	var test map[string]int
	fmt.Println(test == nil)
	// 往nil map写入元素会引发panic
	// test["abc"] = 22

	age, ok := ages["bob"]
	if !ok {
		fmt.Printf("bob is not a key in ages, age==%d\n", age)
	}
	fmt.Println()

	// 不可简单地用 xValue!=y[key]进行判断，会因为0值导致判断错误
	fmt.Println(equal(map[string]int{"A": 0}, map[string]int{"B": 42}))
	fmt.Println(equal(map[string]int{"A": 42}, map[string]int{"A": 42}))
}
